package main

import (
	"fmt"
	"strconv"
	"sync"
	"time"
)

func GetChannelFateList(personCount int) {
	baseFateRate := Rands(0.0, 0.4) //基础体脂率
	chanPerson := make(chan *Person, personCount)
	wg := sync.WaitGroup{}
	wg.Add(personCount)
	for i := 0; i < personCount; i++ {
		go func(num int) {
			defer wg.Done()
			name := "user_channel_No_" + strconv.Itoa(num)
			//每个人的体脂率在每人的基础上±0.2
			fatRate := Rands(baseFateRate-0.2, baseFateRate+0.2)
			p := &Person{}
			p.register(name, fatRate)
			chanPerson <- p
		}(i)
	}
	wg.Wait()
	close(chanPerson)
	maps := updateFatRate(chanPerson)
	for i := 0; i < personCount; i++ {
		go func(num int) {
			name := "user_channel_No_" + strconv.Itoa(num)
			if personInfo, ok := maps.Load(name); ok {
				personInfo := personInfo.(List)
				fmt.Println(name, "当前排名第：", personInfo.index, "其体脂率为:", personInfo.fateRate)
			}
		}(i)
	}
	time.Sleep(2 * time.Second)
}

func updateFatRate(ch chan *Person) (m sync.Map) {
	m = sync.Map{}
	persons := Persons{}
	for person := range ch {
		persons = append(persons, person)
	}
	return SortPerson(persons)
}
